package com.zc.http.okhttp.callback;

import com.zc.http.okhttp.OkHttpUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Response;
import pad.stand.com.haidiyun.www.common.P;

/**
 */
public abstract class FileCallBack extends Callback<File> {
	/**
	 * 鐩爣鏂囦欢瀛樺偍鐨勬枃浠跺す璺緞
	 */
	private String destFileDir;
	/**
	 * 鐩爣鏂囦欢瀛樺偍鐨勬枃浠跺悕
	 */
	private String destFileName;

	public FileCallBack(String destFileDir, String destFileName) {
		this.destFileDir = destFileDir;
		this.destFileName = destFileName;
	}

	@Override
	public File parseNetworkResponse(Response response, int id)
			throws Exception {
		return saveFile(response, id);
	}
	/**
	 * 淇濆瓨鏂囦欢
	 */
	public File saveFile(Response response, final int id) throws IOException {
		InputStream is = null;
		byte[] buf = new byte[2048];
		int len = 0;
		FileOutputStream fos = null;
		try {
			is = response.body().byteStream();
			final long total = response.body().contentLength();
			P.c("什么情况" + total);
			if (total == 0) {
				return null;
			}
			long sum = 0;
			P.c("地址"+destFileDir);
			File dir = new File(destFileDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File file = new File(dir, destFileName);
			fos = new FileOutputStream(file);
			while ((len = is.read(buf)) != -1) {
				sum += len;
				fos.write(buf, 0, len);
				final long finalSum = sum;
				OkHttpUtils.getInstance().getDelivery().execute(new Runnable() {
					@Override
					public void run() {
						// inProgress(finalSum * 1.0f / total,total,id);
						// P.c(finalSum+"-->");
						inProgress(finalSum, total, id);
					}
				});
			}
			fos.flush();

			return file;

		} finally {
			try {
				response.body().close();
				if (is != null)
					is.close();
			} catch (IOException e) {
			}
			try {
				if (fos != null)
					fos.close();
			} catch (IOException e) {
			}

		}
	}

}
